//
//  ZLPSearchViewController.m
//  TangYi
//
//  Created by dllo on 15/10/28.
//  Copyright © 2015年 赵连鹏. All rights reserved.
//

#import "ZLPSearchViewController.h"
#import "ZLPSearchModel.h"
#import "ZLPSearchCollectionViewCell.h"
#import <UIImageView+WebCache.h>
#import "ZLPPicViewController.h"
#import "ZLPResultViewController.h"
#import <AFNetworking.h>
#import <MBProgressHUD.h>



@interface ZLPSearchViewController ()<UICollectionViewDataSource, UICollectionViewDelegate, UISearchBarDelegate>

@property(nonatomic, retain) UICollectionView *collectionView;
@property(nonatomic, retain) NSMutableArray *searchArr;
@property(nonatomic, assign) NSInteger flag;
@property(nonatomic, retain) UISearchBar *searchBar;
@property(nonatomic, retain) UIView *hideView;// 遮盖视图
@property(nonatomic, retain) MBProgressHUD *HUD;
@property(nonatomic, assign) BOOL isNet;


@end

@implementation ZLPSearchViewController

- (void)dealloc {
    [_HUD release];
    [_hideView release];
    [_searchArr release];
    [_searchArr release];
    [_collectionView release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self isWlan];
    
    
    
    
    [self createHideView];
    
    [self createSearchBar];
    
    self.HUD = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.HUD.labelText = @"正在加载..";

    
}

- (void)isWlan {
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    [manager startMonitoring];
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        if (status == 2 || status == 1) {
            
            self.isNet = YES;
            [self createCollectionView];
            
            [self createData];
            
            
        } else {
            
            self.isNet = NO;
            
            [self.HUD removeFromSuperview];
            
//            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"没有网络" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
//            [alert show];
            
            NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
            NSString *docPath = [sandBoxPath stringByAppendingPathComponent:@"search.plist"];
            // 反归档
            NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
            
            self.searchArr = [NSMutableArray array];
            self.searchArr = [ZLPSearchModel baseModelByArr:dic[@"data"]];

            [self createCollectionView];
            
        }
        
    }];
}

#pragma mark create方法
- (void)createHideView{
    self.hideView = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT)] autorelease];
    self.hideView.backgroundColor = [UIColor blackColor];
    self.hideView.alpha = 0.5f;
}

- (void)createSearchBar {
    self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(10, 20, WIDTH - 20, 0)];
    [self.navigationController.navigationBar addSubview:self.searchBar];
    [_searchBar release];
    self.searchBar.placeholder = @"搜索你感兴趣的物品";
//    [self.searchBar setShowsSearchResultsButton:YES]; // 是否显示搜索结果按钮
//    [self.searchBar setInputAccessoryView:self.hideView]; // 添加遮盖视图
    [self.searchBar setShowsScopeBar:YES]; // 是否显示分栏条
//    [self.searchBar setScopeButtonTitles:[NSArray arrayWithObjects:@"1111", @"22222", @"3333", nil]];
//    [self.searchBar setShowsBookmarkButton:YES]; //是否显示右侧的"书图标"
 
    self.searchBar.delegate = self;
//    [self.searchBar sizeToFit];
    
    

    
}

#pragma mark searchBar的协议方法
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    [self.searchBar setShowsCancelButton:YES animated:YES];
    for (UIView *view in [[self.searchBar.subviews lastObject] subviews]) {
        if ([view isKindOfClass:[UIButton class]]) {
            UIButton *cancelBtn = (UIButton *)view;
            [cancelBtn setTitle:@"取消" forState:UIControlStateNormal];
        }
    }
    return YES;
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar {
    [self.searchBar resignFirstResponder];
    [self.searchBar setShowsCancelButton:NO animated:YES];
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSLog(@"搜索~~");
    [self.searchBar resignFirstResponder];
    
    self.searchBar.hidden = YES;
    
    ZLPResultViewController *resultVC = [[ZLPResultViewController alloc] init];
    [self.navigationController pushViewController:resultVC animated:YES];
    
//    resultVC.str = [searchBar.text stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    if ([_searchBar.text  isEqual: @""]) {
        NSLog(@"!!!!!!!!");
        _searchBar.text = @" ";
    }
    
    NSLog(@"%@", searchBar.text);
    resultVC.str = searchBar.text;
    
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText {
    NSLog(@"%@", searchText);
}

#pragma mark createCollectionView
- (void)createCollectionView {
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake(WIDTH / 2 - 20, HEIGHT / 8);
//    layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10);
    if (self.isNet) {
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64 - 49) collectionViewLayout:layout];
    } else {
        self.collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT - 64) collectionViewLayout:layout];
    }
    [self.view addSubview:self.collectionView];
    [_collectionView release];
    
    self.collectionView.backgroundColor = [UIColor whiteColor];
    self.collectionView.showsVerticalScrollIndicator = NO;
    
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    
    [self.collectionView registerClass:[ZLPSearchCollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
}
#pragma mark createData
- (void)createData {
    NSString *strURL = @"http://open3.bantangapp.com/category/list";
    NSURL *url = [NSURL URLWithString:strURL];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [request setHTTPMethod:@"POST"];
    NSString *bodyStr = @"app_installtime=1445349591.654459&app_versions=4.2.2&channel_name=appStore&client_id=bt_app_ios&client_secret=9c1e6634ce1c5098e056628cd66a17a5&oauth_token=8e93baa2127b39cbf64d15bfee8cff56&os_versions=9.0.2&track_device_info=iPhone6%2C2&track_deviceid=A5849E0F-EF33-4B83-80B1-0B846EE0DB3B&track_user_id=1457728&v=7";
    NSData *bodyData = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    [request setHTTPBody:bodyData];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
       
        if (data != nil) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
            
            self.searchArr = [NSMutableArray array];
            self.searchArr = [ZLPSearchModel baseModelByArr:dic[@"data"]];
            
            //        [self.HUD removeFromSuperview];
            [self.collectionView reloadData];
            
            
            // 1. 找到沙盒路径
            NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
            NSString *cachePath = [sandBoxPath stringByAppendingPathComponent:@"search.plist"];
            [NSKeyedArchiver archiveRootObject:dic toFile:cachePath];
            NSLog(@"--%@", cachePath);
        } else {
            [self.HUD removeFromSuperview];
            
            NSString *sandBoxPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)lastObject];
            NSString *docPath = [sandBoxPath stringByAppendingPathComponent:@"search.plist"];
            // 反归档
            NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithFile:docPath];
            
            self.searchArr = [NSMutableArray array];
            self.searchArr = [ZLPSearchModel baseModelByArr:dic[@"data"]];
            
            [self createCollectionView];

        }
  
    }];
    
}

#pragma mark collectionView的协议方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    return self.searchArr.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPSearchCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"collection" forIndexPath:indexPath];
    
    ZLPSearchModel *model = [[ZLPSearchModel alloc] init];
    model = self.searchArr[indexPath.row];
    cell.nameLabel.text = model.name;
    cell.en_nameLabel.text = model.en_name;
    [cell.iconView sd_setImageWithURL:[NSURL URLWithString:model.icon] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    ZLPPicViewController *picVC = [[ZLPPicViewController alloc] init];
    [self.navigationController pushViewController:picVC animated:YES];
    
    ZLPSearchModel *model = [[ZLPSearchModel alloc] init];
    model = self.searchArr[indexPath.row];
    picVC.numID = model.numID;
    picVC.headTitle = model.name;
    self.flag = 1;
    picVC.flag = self.flag;
    
    [self.searchBar resignFirstResponder];
    self.searchBar.hidden = YES;
    
}

- (void)viewWillAppear:(BOOL)animated {
    self.searchBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
